package jjn.round1;

import commons.ListNode;

/**
 * @author Jjn
 * @since 2022/10/7 18:22
 */
public class LeetCode707_MyLinkedList {

    private ListNode dummy;
    private int count;

    public LeetCode707_MyLinkedList() {
        dummy = new ListNode(Integer.MIN_VALUE);
        count = 0;
    }

    public int get(int index) {
        if (index >= count || index < 0) {
            return -1;
        }
        ListNode node = dummy;
        for (int i = 0; i <= index; i++) {
            node = node.next;
        }
        return node.val;
    }

    public void addAtHead(int val) {
        ListNode head = dummy;
        ListNode next = null;
        if (head.next != null) {
            next = head.next;
        }
        head.next = new ListNode(val);
        head = head.next;
        if (next != null) {
            head.next = next;
        }
        count++;
    }

    public void addAtTail(int val) {
        ListNode node = dummy;
        while (node.next != null) {
            node = node.next;
        }
        node.next = new ListNode(val);
        count++;
    }

    public void addAtIndex(int index, int val) {
        if (index <= 0) {
            addAtHead(val);
            return;
        }
        if (index == count) {
            addAtTail(val);
            return;
        }
        if (index > count) {
            return;
        }
        ListNode head = dummy;
        for (int i = 1; i <= index; i++) {
            head = head.next;
        }
        ListNode next = head.next;
        head.next = new ListNode(val);
        head = head.next;
        head.next = next;
        count++;
    }

    public void deleteAtIndex(int index) {
        if (index < 0 || index >= count) {
            return;
        }
        ListNode head = dummy;
        for (int i = 0; i < index; i++) {
            head = head.next;
        }
        ListNode next = head.next;
        if (next != null) {
            head.next = next.next;
        }
        count--;
    }
}
